/*
 * Copyright (c) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class CustomWebView extends StatefulWidget {
  const CustomWebView({super.key});

  @override
  State<CustomWebView> createState() => _CustomWebViewState();
}

class _CustomWebViewState extends State<CustomWebView> {
  late MethodChannel _channel;
  String result = '';
  String inputValue = '';
  bool onlineImageAccess = true;
  bool imageAccess = true;
  bool javaScriptAccess = true;
  bool blockNetwork = false;
  bool zoomAccess = true;

  //
  List<int> defaultFontSizeList = <int>[12,14,16,18,20];
  late int defaultFontSize;

  // 
  List<int> darkModeList = <int>[0,1,2];
  late int darkMode;

  // 
  List<int> initialScaleList = <int>[20,40,60,80,100,120,140];
  late int initialScale;

  double inputHeight = 0;
  late FocusNode _focusNode;

  void _handleFocusChange() {
    if (_focusNode.hasFocus) {
      setState(() {
        inputHeight = 120;
      });
    } else {
      setState(() {
        inputHeight = 0;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
    _focusNode.addListener(_handleFocusChange);
    _channel = const MethodChannel('com.example.platformView.channel/web');
    _channel.setMethodCallHandler(
      (call) async{
        switch(call.method) {
          case 'getMessageFromOhosView':
          // 
            final result = call.arguments as String;
            setState(() {
              this.result = result;
            });
            break;
        }
    });

    defaultFontSize = 16;
    // 
    darkMode = 2;
    initialScale = 100;
  }


  @override
  void dispose(){
    super.dispose();
    _focusNode.removeListener(_handleFocusChange);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          color: Colors.blueAccent.withAlpha(60),
          width: 400,
          height: 400 - inputHeight,
          child: 
            const OhosView(
              viewType: 'com.example.platformView/web'
            ),
        ),
        Column(
          children: [
            TextField(
              focusNode: _focusNode,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'url'
              ),
              onChanged: (value) =>{
                inputValue = value
              },
            ),
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  ElevatedButton(
                    onPressed: () async {
                      await _channel.invokeMethod('changeUrl', inputValue);
                    }, 
                    child: const Text('设置Url')
                  ),
                  ElevatedButton(
                    onPressed: () async {
                      await _channel.invokeMethod('refresh', inputValue);
                    }, 
                    child: const Text('刷新')
                  ),
                  ElevatedButton(
                    onPressed: () async {
                      await _channel.invokeMethod('baclward', inputValue);
                    }, 
                    child: const Text('后退')
                  ),
                  ElevatedButton(
                    onPressed: () async {
                      await _channel.invokeMethod('forward', inputValue);
                    }, 
                    child: const Text('前进')
                  ),
                  ElevatedButton(
                    onPressed: () async {
                      await _channel.invokeMethod('stop', inputValue);
                    }, 
                    child: const Text('后退')
                  ),
                ],
              ),
            ),
            Text("Flutter接收数据：$result"),
          ],
        ),
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              children: [
                Row(
                  children: [
                    const Text("允许从网络加载图片资源"),
                    Switch(
                      value: imageAccess, 
                      onChanged: (value) async {

                        setState(() {
                          onlineImageAccess = value;
                        });
                        await _channel.invokeMethod('onlineImageAccess', value);
                      }
                    )
                  ],
                ),
                Row(
                  children: [
                    const Text("允许自动加载图片资源"),
                    Switch(
                      value: imageAccess, 
                      onChanged: (value) async {

                        setState(() {
                          onlineImageAccess = value;
                        });
                        await _channel.invokeMethod('imageAccess', value);
                      }
                    )
                  ],
                ),
                Row(
                  children: [
                    const Text("允许执行JavaScript脚本"),
                    Switch(
                      value: imageAccess, 
                      onChanged: (value) async {

                        setState(() {
                          onlineImageAccess = value;
                        });
                        await _channel.invokeMethod('javaScriptAccess', value);
                      }
                    )
                  ],
                ),
                Row(
                  children: [
                    const Text("是否阻止从网络加载资源"),
                    Switch(
                      value: imageAccess, 
                      onChanged: (value) async {

                        setState(() {
                          onlineImageAccess = value;
                        });
                        await _channel.invokeMethod('blockNetwork', value);
                      }
                    )
                  ],
                ),
                Row(
                  children: [
                    const Text("是否支持手势进行缩放"),
                    Switch(
                      value: imageAccess, 
                      onChanged: (value) async {

                        setState(() {
                          onlineImageAccess = value;
                        });
                        await _channel.invokeMethod('zoomAccess', value);
                      }
                    )
                  ],
                ),
                Row(
                  children: [
                    const Text("深色模式"),
                    DropdownButton(
                      value: darkMode,
                      items: darkModeList.map<DropdownMenuItem<int>>((int value) {
                        return DropdownMenuItem<int>(
                          value: value,
                          child: Text(value.toString()),
                        );
                      }).toList(),
                      onChanged: (value) async {
                        setState(() {
                          darkMode = value!;
                        });
                        await _channel.invokeMethod('darkMode', value);
                      },
                    )
                  ],
                ),
                Row(
                  children: [
                    const Text("缩放百分百"),
                    DropdownButton(
                      value: initialScale,
                      items: initialScaleList.map<DropdownMenuItem<int>>((int value) {
                        return DropdownMenuItem<int>(
                          value: value,
                          child: Text(value.toString()),
                        );
                      }).toList(),
                      onChanged: (value) async {
                        setState(() {
                          initialScale = value!;
                        });
                        await _channel.invokeMethod('initialScale', value);
                      },
                    )
                  ],
                )
              ]
            ),
          )
        )
      ],
    );
  }
}

class ControllerWidgets extends StatefulWidget {

  const ControllerWidgets({super.key});
  
  @override
  State<StatefulWidget> createState() => _ControllerWidgetsState();
  
}

class _ControllerWidgetsState extends State<ControllerWidgets> {

  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}